<template>
    <div class="art-full-height">
        <!-- 主列表：数据权限规则 -->
        <DataPermissionSearch v-show="showSearchBar" v-model="ruleSearchForm" @search="handleRuleSearch"
            @reset="handleRuleReset" />
        <ElCard class="art-table-card" shadow="never" :style="{ 'margin-top': showSearchBar ? '12px' : '0' }">

            <ArtTableHeader v-model:show-search-bar="showSearchBar" v-model:columns="ruleColumnChecks"
                :loading="ruleLoading" @refresh="ruleRefresh">
                <template #left>
                    <ElSpace wrap>
                        <ElButton v-auth="'add'" type="primary" @click="showRuleDialog('add')" v-ripple>新增规则</ElButton>
                    </ElSpace>
                </template>
            </ArtTableHeader>

            <ArtTable rowKey="id" :loading="ruleLoading" :data="ruleData" :columns="ruleColumns"
                :pagination="rulePagination" @pagination:size-change="handleRuleSizeChange"
                @pagination:current-change="handleRuleCurrentChange" />
        </ElCard>

        <!-- 右侧抽屉：角色权限关联 -->
        <ElDrawer v-model="rolePermissionDrawerVisible" direction="rtl" :with-header="false" size="60%">
            <div class="drawer-content">
                <div class="drawer-header">
                    <div class="header-left">
                        <b>使用该规则的角色列表</b>
                        <span v-if="selectedRuleId" class="sub">当前规则：{{ selectedRuleName }}（ID: {{ selectedRuleId
                        }}）</span>
                    </div>
                    <div class="header-actions">
                        <ElButton type="primary" :disabled="!selectedRuleId" v-auth="'add'"
                            @click="showRolePermissionDialog('add')" v-ripple>
                            添加角色关联
                        </ElButton>
                    </div>
                </div>

                <ArtTable rowKey="id" :loading="rolePermissionLoading" :data="rolePermissionData"
                    :columns="rolePermissionColumns" :showTableHeader="false" />
            </div>
        </ElDrawer>

        <!-- 弹窗：数据权限规则 -->
        <DataPermissionDialog v-model:visible="ruleDialogVisible" :type="ruleDialogType" :editData="currentRuleData"
            @submit="handleRuleDialogSubmit" />

        <!-- 弹窗：角色权限关联 -->
        <RolePermissionDialog v-model:visible="rolePermissionDialogVisible" :type="rolePermissionDialogType"
            :rule-id="selectedRuleId" :edit-data="currentRolePermissionData"
            @submit="handleRolePermissionDialogSubmit" />
    </div>
</template>

<script setup lang="ts">
import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
import { useTable } from '@/composables/useTable'
import {
    fetchDataPermissionRuleList,
    deleteDataPermissionRule,
    fetchRuleRolePermissions,
    deleteRoleDataPermission,
    type RoleDataPermissionResponse,
    type DataPermissionRuleResponse
} from '@/api/system/data-permission'
import DataPermissionSearch from './modules/data-permission-search.vue'
import DataPermissionDialog from './modules/data-permission-dialog.vue'
import RolePermissionDialog from './modules/role-permission-dialog.vue'
import { useSystemStore } from '@/store/modules/system'

defineOptions({ name: 'DataPermissionManage' })


const system = useSystemStore()
const showSearchBar = ref(false)

// 左侧：数据权限规则搜索表单
const ruleSearchForm = ref<any>({
    rule_name: undefined,
    table_name: undefined,
    rule_type: undefined,
    is_active: undefined,
    keyword: undefined
})

// 当前选中的数据权限规则
const selectedRuleId = ref<number | null>(null)
const selectedRuleName = ref<string>('')
const roles = computed(() => system.getRoles)

// 规则列表 useTable
const {
    data: ruleData,
    columns: ruleColumns,
    columnChecks: ruleColumnChecks,
    loading: ruleLoading,
    pagination: rulePagination,
    refreshData: ruleRefresh,
    handleSizeChange: handleRuleSizeChange,
    handleCurrentChange: handleRuleCurrentChange,
    searchParams: ruleSearchParams,
    getData: getRuleData
} = useTable({
    core: {
        apiFn: fetchDataPermissionRuleList,
        apiParams: {
            current: 1,
            size: 20,
            ...ruleSearchForm.value
        },
        immediate: false,
        columnsFactory: () => [
            { prop: 'id', label: 'ID', width: 80, checked: false },
            { prop: 'rule_code', label: '规则编码' },
            { prop: 'name', label: '名称', minWidth: 200 },
            { prop: 'table_name', label: '表名' },
            { prop: 'logical_operator', label: '操作符', width: 80 },
            { prop: 'condition_type', label: '条件类型', width: 100 },
            {
                prop: 'config_json',
                label: '配置信息',
                minWidth: 250,
                formatter: (row: any) => {
                    if (typeof row.config_json === 'object' && row.config_json !== null) {
                        return JSON.stringify(row.config_json, null, 2);
                    }
                    return row.config_json;
                }
            },
            { prop: 'description', label: '描述', minWidth: 200, checked: false },
            {
                prop: 'status',
                label: '状态',
                width: 80,
                formatter: (row: RoleDataPermissionResponse) =>
                    h('span', { class: row.status ? 'text-green-600' : 'text-red-600' },
                        row.status ? '启用' : '禁用')
            },
            { prop: 'create_time', label: '创建时间', width: 160, checked: false },
            { prop: 'update_time', label: '更新时间', width: 160, checked: false },
            {
                prop: 'operation',
                label: '操作',
                width: 165, // 增加宽度以容纳新按钮
                aglin: 'right',
                formatter: (row: DataPermissionRuleResponse) =>
                    h('div', [
                        h(ArtButtonTable, {
                            type: 'view', // 新增的按钮
                            onClick: () => handleRuleRowClick(row)
                        }),
                        h(ArtButtonTable, {
                            type: 'edit',
                            onClick: () => showRuleDialog('edit', row)
                        }),
                        h(ArtButtonTable, {
                            type: 'delete',
                            onClick: () => handleDeleteRule(row)
                        })
                    ])
            }
        ]
    }
})

// 角色权限关联列表（依赖 selectedRuleId，展示在抽屉内）
const {
    data: rolePermissionData,
    columns: rolePermissionColumns,
    loading: rolePermissionLoading,
    refreshData: rolePermissionRefresh,
    getData: getRolePermissionData,
    searchParams: rolePermissionSearchParams
} = useTable({
    core: {
        apiFn: (params: any) => fetchRuleRolePermissions(params.ruleId),
        immediate: false,
        columnsFactory: () => [
            { prop: 'id', label: 'ID', width: 80, checked: false },
            { prop: 'role_id', label: '角色ID', width: 100 },
            {
                prop: 'role_name', label: '角色名称', width: 100,
                formatter: (row: RoleDataPermissionResponse) => roles.value.filter(r => r.id === row.role_id)[0]?.name || '未知角色'
            },
            { prop: 'rule_id', label: '规则ID', width: 100, checked: false },
            {
                prop: 'status',
                label: '状态',
                width: 80,
                formatter: (row: RoleDataPermissionResponse) =>
                    h('span', { class: row.status ? 'text-green-600' : 'text-red-600' },
                        row.status ? '启用' : '禁用')
            },
            { prop: 'create_time', label: '创建时间' },
            {
                prop: 'operation',
                label: '操作',
                width: 120,
                aglin: 'right',
                formatter: (row: RoleDataPermissionResponse) =>
                    h('div', [
                        h(ArtButtonTable, {
                            type: 'delete',
                            onClick: () => handleDeleteRolePermission(row)
                        })
                    ])
            }
        ]
    }
})

// 点击规则打开右侧抽屉并载入角色权限关联
const rolePermissionDrawerVisible = ref(false)
const handleRuleRowClick = (row: DataPermissionRuleResponse) => {
    selectedRuleId.value = row.id ?? null
    selectedRuleName.value = (row as any).name
    rolePermissionDrawerVisible.value = true
        // 记录当前 ruleId 到表格的搜索参数，确保刷新时不会丢失
        ; (rolePermissionSearchParams as any).ruleId = row.id
    // 使用已记录的参数加载数据
    getRolePermissionData()
}

// 规则搜索与重置
const handleRuleSearch = (params: Record<string, any>) => {
    const keys = ['name', 'table_name', 'condition_type', 'status', 'keyword']
    const sp = ruleSearchParams as Record<string, any>
    keys.forEach((k) => {
        sp[k] = params[k] ?? undefined
    })
    ruleSearchParams.current = 1
    getRuleData()
}
const handleRuleReset = () => {
    const keys = ['name', 'table_name', 'condition_type', 'status', 'keyword']
    const sp = ruleSearchParams as Record<string, any>
    keys.forEach((k) => delete sp[k])
    ruleSearchParams.current = 1
    getRuleData()
}

// 弹窗：规则
const ruleDialogVisible = ref(false)
const ruleDialogType = ref<'add' | 'edit'>('add')
const currentRuleData = ref<Partial<DataPermissionRuleResponse>>({})
const showRuleDialog = (type: 'add' | 'edit', row?: DataPermissionRuleResponse) => {
    ruleDialogType.value = type
    currentRuleData.value = row || {}
    nextTick(() => {
        ruleDialogVisible.value = true
    })
}
const handleRuleDialogSubmit = async () => {
    ruleDialogVisible.value = false
    currentRuleData.value = {}
    ruleRefresh()
}

// 弹窗：角色权限关联
const rolePermissionDialogVisible = ref(false)
const rolePermissionDialogType = ref<'add' | 'edit'>('add')
const currentRolePermissionData = ref<Partial<RoleDataPermissionResponse>>({})
const showRolePermissionDialog = (type: 'add' | 'edit', row?: RoleDataPermissionResponse) => {
    if (!selectedRuleId.value) {
        ElMessage.warning('请先选择数据权限规则')
        return
    }
    rolePermissionDialogType.value = type
    currentRolePermissionData.value = row || {}
    nextTick(() => {
        rolePermissionDialogVisible.value = true
    })
}
const handleRolePermissionDialogSubmit = async () => {
    rolePermissionDialogVisible.value = false
    currentRolePermissionData.value = {}
        // 刷新前确保 ruleId 参数存在
        ; (rolePermissionSearchParams as any).ruleId = selectedRuleId.value
    rolePermissionRefresh()
}

// 删除：规则
const handleDeleteRule = async (row: DataPermissionRuleResponse) => {
    try {
        await ElMessageBox.confirm(`确定要删除该数据权限规则吗？`, '删除数据权限规则', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        const id = Number(row?.id)
        if (!id) {
            ElMessage.error('缺少规则ID，无法删除')
            return
        }
        await deleteDataPermissionRule(id)
        ElMessage.success('删除成功')
        ruleRefresh()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败，请稍后重试')
        }
    }
}

// 删除：角色权限关联
const handleDeleteRolePermission = async (row: RoleDataPermissionResponse) => {
    try {
        await ElMessageBox.confirm('确定要删除这个角色权限关联吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        await deleteRoleDataPermission(row.id)
        ElMessage.success('删除成功')
        rolePermissionRefresh()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 初次加载规则列表
onMounted(async () => {
    await getRuleData()
})
</script>

<style lang="scss" scoped>
.art-table-card {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.drawer-content {
    display: flex;
    flex-direction: column;
    gap: 12px;
    height: 100%;
}

.drawer-header {
    display: flex;
    gap: 8px;
    align-items: baseline;
    margin-bottom: 8px;
    justify-content: space-between;

    .header-left {
        display: flex;
        gap: 8px;
        align-items: baseline;
    }

    .header-actions {
        display: flex;
        align-items: center;
    }

    .sub {
        color: var(--el-text-color-secondary);
        font-size: 13px;
    }
}
</style>
<style lang="scss">
/* 取消抽屉内部滚动限制 */
.el-drawer__body {
    display: flex;
    flex-direction: column;
}

.el-drawer__body .drawer-content {
    flex: 1;
}
</style>